#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：视频音频分离.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/4/26 上午11:00 
"""

import os
import subprocess
import time
from tqdm import tqdm
import tkinter as tk
from tkinter import filedialog


def extract_audio_from_video(video_path, output_audio_path, verbose=False):
	"""分离音频并保存到指定路径"""
	# 指定 ffmpeg 的完整路径（根据实际路径修改）
	ffmpeg_path = r"D:\myapps\ffmpeg-7.1.1-full_build\bin\ffmpeg.exe"  # 修改为你的ffmpeg路径
	command = [
		ffmpeg_path, '-i', video_path, '-vn', '-acodec', 'copy', output_audio_path
	]
	try:
		subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
		if verbose:
			print(f"音频提取成功：{output_audio_path}")
	except subprocess.CalledProcessError as e:
		if verbose:
			print(f"音频提取失败：{video_path} -> {output_audio_path}. 错误：{e}")


def process_videos_in_directory(directory_path, verbose=False):
	"""处理视频文件夹中的所有MP4文件"""
	# 获取目录下的所有MP4文件
	video_files = [f for f in os.listdir(directory_path) if f.endswith('.mp4')]

	if not video_files:
		if verbose:
			print("没有找到MP4视频文件.")
		return

	start_time = time.time()

	# 显示进度条
	for video_file in tqdm(video_files, desc="处理视频文件", unit="个", ncols=100):
		video_path = os.path.join(directory_path, video_file)
		audio_output_path = os.path.join(directory_path, video_file.replace('.mp4', '.aac'))

		# 检查是否已经存在同名音频文件，若存在则删除
		if os.path.exists(audio_output_path):
			if verbose:
				print(f"检测到已存在音频文件，准备删除：{audio_output_path}")
			os.remove(audio_output_path)

		# 分离音频
		extract_audio_from_video(video_path, audio_output_path, verbose)

	end_time = time.time()
	total_time = end_time - start_time
	if verbose:
		print(f"处理完毕！总耗时: {total_time:.2f}秒")


def select_directory():
	"""使用tkinter打开文件夹选择对话框"""
	root = tk.Tk()
	root.withdraw()  # 隐藏主窗口
	folder_selected = filedialog.askdirectory(title="选择视频文件夹")
	return folder_selected


if __name__ == '__main__':
	# 通过文件对话框选择文件夹
	directory_path = select_directory()

	# 设置 verbose 为 True 以打开输出，或者保持为 False 以禁止输出
	verbose_mode = False  # 控制是否输出过程信息，默认为 False

	if directory_path:  # 确保选择了文件夹
		process_videos_in_directory(directory_path, verbose=verbose_mode)
	else:
		if verbose_mode:
			print("未选择文件夹，程序结束。")
